//
//  PhotoBrowserItem.swift
//  Weibo
//
//  Created by 李亚乐 on 15/12/19.
//  Copyright © 2015年 李亚乐. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

protocol PhotoBrowserItemDelegate: NSObjectProtocol {
    func PhotoBrowserItemDidTappedImage()
}

// MARK: - 自定义 Item
class PhotoBrowserItem: UICollectionViewCell {
    
    weak var photoDelegate: PhotoBrowserItemDelegate?
    
    @objc private func tapImgae() {
        photoDelegate?.PhotoBrowserItemDidTappedImage()
    }
    
//    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//        photoDelegate?.PhotoBrowserItemDidTappedImage()
//    }
    
    ///  缩略图片 url
    var imageURL: NSURL? {
        didSet {
            
            guard let url = imageURL else {
                return
            }
            
            resetScrollView()
            
            resetPlaceholder(url)
            
            imgView.sd_setImageWithURL(bmiddleURL(url),
                placeholderImage: nil,
                options: [SDWebImageOptions.RefreshCached, SDWebImageOptions.RetryFailed],
                progress: { (current, total) -> Void in
                
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        let progress = CGFloat(current) / CGFloat(total)
                        self.progressview.progress = progress
                    })
                    
                }) { (image, _, _, _) -> Void in
                    
                    if image == nil {
                        SVProgressHUD.showInfoWithStatus("网络不给力")
                        return
                    }
                    self.setPosition(image)
                    self.placeholderImg.hidden = true
            }
        }
    }
    
    // MARK: - 视图生命周期
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 懒加载控件
    /// 缩放视图
    var zoomView: UIScrollView = UIScrollView()
    /// 加载大图
    var imgView: UIImageView = UIImageView()
    /// 占位小图
    private lazy var placeholderImg: UIImageView = UIImageView()
    private lazy var progressview: ProgressView = ProgressView()
    
// MARK: - 设置 UI 界面
    private func setupUI() {
        /// 添加缩放视图
        contentView.addSubview(zoomView)
        
        zoomView.addSubview(imgView)
        contentView.addSubview(placeholderImg)
        /// 添加进度视图
        placeholderImg.addSubview(progressview)
        progressview.backgroundColor = UIColor.clearColor()
        progressview.snp_makeConstraints { (make) -> Void in
            make.width.equalTo(50)
            make.height.equalTo(50)
            make.center.equalTo(placeholderImg)
        }
        
        var rect = bounds
        rect.size.width -= 20
        zoomView.frame = rect

        zoomView.delegate = self
        zoomView.maximumZoomScale = 2.0
        zoomView.minimumZoomScale = 0.5
        
        let tap = UITapGestureRecognizer(target: self, action: "tapImgae")
        imgView.userInteractionEnabled = true
        imgView.addGestureRecognizer(tap)
    }
    
/// 重置视图 防止Cell 重用
    private func resetScrollView() {
        imgView.transform = CGAffineTransformIdentity
        
        zoomView.contentOffset = CGPointZero
        zoomView.contentSize = CGSizeZero
        zoomView.contentInset = UIEdgeInsetsZero
    }
    
    private func resetPlaceholder(url: NSURL) {
        let manager = SDWebImageManager.sharedManager()
        let img = manager.imageCache.imageFromDiskCacheForKey(url.absoluteString)
        placeholderImg.image = img
        placeholderImg.hidden = false
        placeholderImg.sizeToFit()
        placeholderImg.center = zoomView.center
    }
}

// MARK: - 滚动视图代理方法
extension PhotoBrowserItem: UIScrollViewDelegate {
    
    /// 需要放大的 View
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imgView
    }
    
    /// 缩放时调用
    func scrollViewDidZoom(scrollView: UIScrollView) {
//        print(imgView.transform)
    }
    
    /// 缩放结束时调用
    ///
    /// - parameter view:       被缩放的视图
    /// - parameter scale:      缩放比例
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        print(view)
        var offsetY = (zoomView.bounds.height - view!.frame.height) / 2
        var offsetX = (zoomView.bounds.width - view!.frame.width) / 2
        offsetY = offsetY < 0 ? 0 : offsetY
        offsetX = offsetX < 0 ? 0 : offsetX
        
        zoomView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, 0, 0)
    }
}

// MARK: - 大图配置 设置
extension PhotoBrowserItem {
    /// 转换大图地址
    ///
    /// - parameter url: 缩略图地址
    ///
    /// - returns: 大图地址
    private func bmiddleURL(url: NSURL) -> NSURL {
        var urlString = url.absoluteString
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        
        return NSURL(string: urlString)!
    }
    
    /// 设置图片位置
    private func setPosition(image: UIImage) {
        
        /// 根据 '大图' 计算宽高
        let width = zoomView.bounds.width
        let height = image.size.height * width / image.size.width
        
        //判断大图高度 设置滚动视图位置
        if height < zoomView.bounds.height { //居中
            let Y = (zoomView.bounds.height - height) / 2
            imgView.frame = CGRect(x: 0, y: 0, width: width, height: height)
            
            zoomView.contentInset = UIEdgeInsetsMake(Y, 0, 0, 0)
        } else {
            imgView.frame = CGRect(x: 0, y: 0, width: width, height: height)
            zoomView.contentSize = CGSize(width: width, height: height)
        }
    }
}



